package com.cloudcc.mobile.view.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.NewcontactEditAdapter;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.easemob.util.NetUtils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.bean.RoleAuthority;
import com.mypage.model.ContactDelece;
import com.mypage.utils.AnimViewUtils;
import com.mypage.view.activity.NewContactLianXi;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CreatContact extends BaseActivity {
    ImageView Contact_edit_return;
    ImageView Contact_edit_save;
    TextView edit_kehumingcheng;
    TextView edit_contact_name;
    Button edit_btn_contactjuese;
    @Bind(R.id.btnContent)
    Button btnContent;
    @Bind(R.id.layoutTop)
    FrameLayout layoutTop;
    private List<String> mList;
    private NewcontactEditAdapter mAdapter;
    private String isdefault="0";
    private String jueseid = "";
    private String  recordId,layoutId,relatedlistId;
    private String lianxiren_id = "";
    private CheckBox edit_check;
    private ImageView imageView;

    private RelativeLayout topLayoutBackg;
    private TextView toastHintContent;
    private ImageView imgDeletes;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_creat_contact);
        ButterKnife.bind(this);
        initView();
        initdata();
        addlistenr();
    }
    @Override
    public int getLayoutId() {
        return R.layout.activity_creat_contact;
    }
    private void initView() {
        imageView = (ImageView) findViewById(R.id.imagecreat);
        Contact_edit_return = (ImageView) findViewById(R.id.Contact_edit_return);
        Contact_edit_save = (ImageView) findViewById(R.id.Contact_edit_save);
        edit_kehumingcheng = (TextView) findViewById(R.id.edit_kehumingcheng);
        edit_contact_name = (TextView) findViewById(R.id.edit_contact_name);
        edit_btn_contactjuese = (Button) findViewById(R.id.edit_btn_contactjuese);
        edit_check = (CheckBox)findViewById(R.id.edit_check);
        Contact_edit_return.setImageDrawable(getResources().getDrawable(R.drawable.fujin_back));
        Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_default));
        imageView.setImageDrawable(getResources().getDrawable(R.drawable.contactperson_find_default));

        toastHintContent = (TextView) findViewById(R.id.toastHintContent);
        imgDeletes = (ImageView) findViewById(R.id.imgDeletes);
        topLayoutBackg = (RelativeLayout) findViewById(R.id.topLayoutBackg);




    }

    @Override
    protected void onResume() {
        super.onResume();
        Contact_edit_return.setImageDrawable(getResources().getDrawable(R.drawable.fujin_back));
        Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_default));
        imageView.setImageDrawable(getResources().getDrawable(R.drawable.contactperson_find_default));
    }

    private void addlistenr() {
        imgDeletes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                imgDeletes.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_close_pressed));
                layoutTop.setVisibility(View.GONE);
            }
        });


        Contact_edit_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Contact_edit_return.setImageDrawable(getResources().getDrawable(R.drawable.fujin_back));
                finish();
            }
        });
        //保存
        Contact_edit_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if("".equals(lianxiren_id)){
                    topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                    toastHintContent.setText(getString(R.string.xuanzelianxiren));
                    //                    Toast.makeText(CreatContact.this,"请选择联系人",1).show();
                    topLayoutBackg.setVisibility(View.GONE);
                    layoutTop.setVisibility(View.VISIBLE);
                    new AnimViewUtils().appearToast(topLayoutBackg);
                    Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_default));

                    return;
                }
                Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_pressed));
                if("".equals(jueseid)){
                    topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                    toastHintContent.setText(getString(R.string.contactxuanze));
//                    Toast.makeText(CreatContact.this,"",1).show();
                    topLayoutBackg.setVisibility(View.GONE);
                    layoutTop.setVisibility(View.VISIBLE);
                    new AnimViewUtils().appearToast(topLayoutBackg);
                    Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_default));
                    return;
                }

                if("".equals(isdefault)){
                    topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_beau));
                    toastHintContent.setText(R.string.shifouzhuyao);
//                    Toast.makeText(CreatContact.this,"请选择是否是主要联系人",1).show();
                    topLayoutBackg.setVisibility(View.GONE);
                    layoutTop.setVisibility(View.VISIBLE);
                    new AnimViewUtils().appearToast(topLayoutBackg);
                    Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_default));

                    return;
                }
                if(NetUtils.hasNetwork(CreatContact.this)){
                    request();
                }else{
                    topLayoutBackg.setBackground(getResources().getDrawable(R.drawable.toast_hint_red));
                    toastHintContent.setText(getString(R.string.meg_net_no));
                    //                    Toast.makeText(CreatContact.this,"请选择是否是主要联系人",1).show();
                    topLayoutBackg.setVisibility(View.GONE);
                    layoutTop.setVisibility(View.VISIBLE);
                    new AnimViewUtils().appearToast(topLayoutBackg);
                    Contact_edit_save.setImageDrawable(getResources().getDrawable(R.drawable.contactpersonrole_confirm_default));
                }

            }
        });
//        //客户名称
//        edit_kehumingcheng.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(CreatContact.this,BeauInfoActivity.class);
//                intent.putExtra("web",kehu_id);
//                startActivity(intent);
//
//            }
//        });
        //选择角色
        edit_btn_contactjuese.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                initPopwindow();

                showPopupWindow(edit_btn_contactjuese);
            }
        });
        edit_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    edit_check.setBackground(getResources().getDrawable(R.drawable.contactpersonrole_jurisdiction_selected));
                    isdefault = "1";
                }else{
                    edit_check.setBackground(getResources().getDrawable(R.drawable.contactpersonrole_jurisdiction_unselected));
                    isdefault = "0";
                }
            }
        });
    }

    private void initdata() {
        Intent intent = getIntent();
        recordId = intent.getStringExtra("recordId");
        layoutId = intent.getStringExtra("layoutId");
        relatedlistId = intent.getStringExtra("relatedlistId");
        initPopwindow();
    }
    private RoleAuthority ss = null;
    public void initPopwindow(){
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "saveOpportunityRoleInit");
        params.addBodyParameter("opportunityId", recordId);
        Log.d("request",
                "链接" + UrlManager.getInterfaceUrl()
                        + GsonUtil.Object2Json(params));
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("-------------------------", "Failure。。。"
                                + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        String result = arg0.result;
                        Log.d("request",
                                "Success_down:     " + result);
                        Gson gson = new Gson();
                        ss = gson.fromJson(result,RoleAuthority.class);
                        edit_kehumingcheng.setText(ss.data.accountName);
//                        showPopupWindow(edit_btn_contactjuese);
                    }
                });

    }
    public void showPopupWindow(View v) {
        View contentView = View.inflate(this, R.layout.popup_role, null);
        final PopupWindow popupWindow = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        ListView popList = (ListView) contentView.findViewById(R.id.popList);
        popupWindow.setTouchable(true);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        setShowListView(popList, popupWindow);
        // 设置好参数之后再show
        if (android.os.Build.VERSION.SDK_INT >=24) {
            int[] a = new int[2];
            v.getLocationInWindow(a);
            popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.NO_GRAVITY, 0 , a[1]+v.getHeight());
        } else{
            popupWindow.showAsDropDown(v);
        }
//        popupWindow.showAsDropDown(v);
    }

    public void setShowListView(ListView popList, PopupWindow popupWindow) {
        if(null==ss||null==ss.data){
            return;
        }
        mAdapter = new NewcontactEditAdapter(CreatContact.this, ss.data.roles);
        popList.setAdapter(mAdapter);
        setPopListnener(popList, popupWindow);
    }

    public void setPopListnener(ListView popList, final PopupWindow popupWindow) {
        popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
                edit_btn_contactjuese.setText(ss.data.roles.get(position).value.toString());
                jueseid = ss.data.roles.get(position).id;
            }
        });
    }

    private String mEns = RunTimeManager.getInstance().getlanguage();

    @OnClick(R.id.btnContent)
    public void onViewClicked() {
        imageView.setImageDrawable(getResources().getDrawable(R.drawable.contactperson_find_pressed));
        Intent intent = new Intent(this, NewContactLianXi.class);
        intent.putExtra("recordId",recordId);
        intent.putExtra("recordId", recordId);
        intent.putExtra("relatedlistId", relatedlistId);
        if ("en".equals(mEns)) {
            intent.putExtra("User", "User");
        } else {
            intent.putExtra("User", "用户");
        }
        layoutTop.setVisibility(View.GONE);
        startActivityForResult(intent, 1);
    }
private String kehu_id;
    private String lianxiren_name;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        lianxiren_name = data.getStringExtra("Name");
        btnContent.setText(data.getStringExtra("Name"));
//        btnContent.setTextColor(getResources().getColor());
//        String mId = data.getStringExtra("mId");
//        edit_kehumingcheng.setText(data.getStringExtra("kehu_name"));
        kehu_id = data.getStringExtra("kehu_id");
        lianxiren_id  = data.getStringExtra("mId");

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void request(){
        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "saveOpportunityRole");
        createJson();
        params.addBodyParameter("data",mdata);
        Log.d("request",
                "链接" + UrlManager.getInterfaceUrl()
                        + GsonUtil.Object2Json(params));
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("-------------------------", "Failure。。。"
                                + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        String result = arg0.result;
                        Log.d("request",
                                "Success_down:     " + result);
                        //                        {"result":true,"returnInfo":"","returnCode":"1","data":null}
                        Gson gson = new Gson();
                        ContactDelece ss = gson.fromJson(result,
                                ContactDelece.class);
                        if("true".equals(ss.result)&&"1".equals(ss.returnCode)){
                            NewContact.instance.finish();
                            Intent intent = new Intent(CreatContact.this,NewContact.class);
                            intent.putExtra("recordId",recordId);
                            intent.putExtra("layoutId",layoutId);
                            intent.putExtra("relatedlistId",relatedlistId);
                            intent.putExtra("tag","xinjian");
                            intent.putExtra("chengg","chengg");
                            intent.putExtra("name",lianxiren_name);
                            startActivity(intent);
                            finish();
                        }else{
                            NewContact.instance.finish();
                            Intent intent = new Intent(CreatContact.this,NewContact.class);
                            intent.putExtra("recordId",recordId);
                            intent.putExtra("layoutId",layoutId);
                            intent.putExtra("relatedlistId",relatedlistId);
                            intent.putExtra("tag","xinjian");
                            intent.putExtra("chengg","shib");
                            startActivity(intent);
                            finish();

                        }

                    }
                });
    }
    private String mdata=null;
    // 把数据转换成json格式。用于上传服务端
    public void createJson() {
        JSONObject object = new JSONObject();
        try {
            object.put("id", "");
            object.put("opportunity", recordId);
            object.put("role", jueseid);
            object.put("isDefault", isdefault);
            object.put("contact", lianxiren_id);
            mdata = object.toString();
            mdata = "["+mdata+"]";
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
